import axios from 'axios'
import {Message, MessageBox} from 'element-ui'
import store from '../store'
import { getToken, setToken ,removeToken} from '@/utils/auth'
import router from '../router'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_URL, // api的base_url
  timeout: 30000                  // 请求超时时间 设置为30秒
})
// request拦截器
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (getToken()) {
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const token = response.headers.authorization
    if (token) {
      setToken(token)
    }

    const res = response.data
    return res
  },
  error => {
    if (error.response) {
      if (error.response.status === 500) {
        let msg = error.message
        if (error.response.data) {
          msg = error.response.data
        }
        Message.error({
          message: msg,
          type: 'error',
          duration: 3 * 1000
        })
        // eslint-disable-next-line eqeqeq
      } else if (error.response.status === 504 || error.response.status === 404) {
        Message.error({
          message: '服务器被吃了⊙﹏⊙∥',
          type: 'error',
          duration: 3 * 1000
        })
      } else if (error.response.status === 403) {
        Message.error({
          message: '权限不足,请联系管理员!',
          type: 'error',
          duration: 3 * 1000
        })
      }else if (error.response.status === 401) {
        removeToken();
        router.push({name: 'login'});
        Message.error({
          message: '登录信息失效',
          type: 'error',
          duration: 3 * 1000
        })
      }
    } else {
      Message.error({
        message: error.msg,
        type: 'error',
        duration: 3 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service

